"use client";
import React, { forwardRef, useImperativeHandle } from "react";
import Image from "next/image";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { RegisterSchema } from "@/schemas";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";

export interface RegisterFormRef {
  onSubmit: () => void;
}

type FormProps = {
  handleSubmit: (values: z.infer<typeof RegisterSchema>) => void;
} & React.ComponentProps<"div"> & {
    imageUrl?: string;
  };
const RegisterForm = forwardRef<RegisterFormRef, FormProps>(
  ({ handleSubmit, className, imageUrl, ...props }, ref) => {
    const form = useForm<z.infer<typeof RegisterSchema>>({
      resolver: zodResolver(RegisterSchema),
      defaultValues: {
        name: "",
        password: "",
        email: "",
      },
    });

    useImperativeHandle(ref, () => ({
      onSubmit: async () => {
        try {
          const isValid = await form.trigger();
          if (isValid) {
            const values = form.getValues();
            handleSubmit(values);
          } else {
            console.log("Validation failed");
          }
        } catch (error) {
          console.error("Error during form submission:", error);
        }
      },
    }));
    return (
      <div className={cn("flex flex-col gap-6", className)} {...props}>
        <Card className="overflow-hidden p-0">
          <CardContent className="grid p-0 md:grid-cols-2">
            <Form {...form}>
              <form className="p-6 md:p-8">
                <div className="flex flex-col gap-6">
                  <div className="flex flex-col items-center text-center">
                    <h1 className="text-2xl font-bold">欢迎</h1>
                    <p className="text-muted-foreground text-balance">注册</p>
                  </div>

                  <FormField
                    control={form.control}
                    name="name"
                    render={({ field }) => (
                      <FormItem className="grid gap-3">
                        <FormLabel
                          htmlFor="id_name"
                          className="text-sm font-medium text-gray-700"
                        >
                          用户名
                        </FormLabel>
                        <FormControl>
                          <Input
                            id="id_name"
                            {...field}
                            placeholder="请输入用户名"
                          />
                        </FormControl>
                        <FormMessage className="text-sm text-red-500" />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="email"
                    render={({ field }) => (
                      <FormItem className="grid gap-3">
                        <FormLabel
                          htmlFor="id_name"
                          className="text-sm font-medium text-gray-700"
                        >
                          邮箱
                        </FormLabel>
                        <FormControl>
                          <Input
                            id="id_email"
                            {...field}
                            placeholder="m@g.com"
                          />
                        </FormControl>
                        <FormMessage className="text-sm text-red-500" />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="password"
                    render={({ field }) => (
                      <FormItem className="grid gap-3">
                        <FormLabel
                          htmlFor="id_password"
                          className="text-sm font-medium text-gray-700"
                        >
                          密码
                        </FormLabel>
                        <FormControl>
                          <Input
                            id="id_password"
                            type="password"
                            {...field}
                            placeholder="请输入用户名"
                          />
                        </FormControl>
                        <FormMessage className="text-sm text-red-500" />
                      </FormItem>
                    )}
                  />
                  <Button
                    className="w-full"
                    onClick={async (e) => {
                      e.preventDefault();
                      try {
                        const isValid = await form.trigger();
                        if (isValid) {
                          const values = form.getValues();
                          handleSubmit(values);
                        } else {
                          console.log("Validation failed");
                        }
                      } catch (error) {
                        console.error("Error during form submission:", error);
                      }
                    }}
                  >
                    注册
                  </Button>
                  <a
                    href="/auth/login"
                    className="ml-auto text-sm underline-offset-2 hover:underline"
                  >
                    已有账户?登陆
                  </a>
                </div>
              </form>
            </Form>
            <div className="bg-primary/50 relative hidden md:block">
              {imageUrl && (
                <Image
                  fill
                  src={imageUrl}
                  alt="Image"
                  className="absolute inset-0 h-full w-full object-cover"
                />
              )}
            </div>
          </CardContent>
        </Card>
        <div className="text-muted-foreground *:[a]:hover:text-primary text-center text-xs text-balance *:[a]:underline *:[a]:underline-offset-4">
          By clicking continue, you agree to our{" "}
          <a href="#">Terms of Service</a> and <a href="#">Privacy Policy</a>.
        </div>
      </div>
    );
  },
);
export { RegisterForm };
